package com.agp.config;

import com.agp.entity.EnvironmentService;
import com.huaweicloud.sdk.iot.device.IoTDevice;
import com.huaweicloud.sdk.iot.device.client.ClientConf;
import com.huaweicloud.sdk.iot.device.client.requests.CommandRsp;
import com.huaweicloud.sdk.iot.device.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

//@Configuration
@Slf4j
public class IotDeviceConfig {

    @Value("classpath:ClientConf.json")
    private File clientConfFile;

    private IoTDevice device;
    private EnvironmentService environmentService;
    private int SLEEP_TIME = 5000;

    @PostConstruct
    public void init() throws IOException {
        String content = FileUtils.readFileToString(clientConfFile, "UTF-8");
        ClientConf clientConf = JsonUtil.convertJsonStringToObject(content, ClientConf.class);

        device = new IoTDevice(clientConf);
        environmentService = new EnvironmentService();
        device.addService("ancientTree1", environmentService);

        if (device.init() != 0) {
            log.error("IoTDevice 初始化失败");
            return;
        }

        log.info("连接成功");

        // 设置命令监听器以处理来自服务器的命令请求
        device.getClient().setCommandListener((requestId, serviceId, commandName, paras) -> {
            // 创建一个表示成功的命令响应对象
            CommandRsp commandRsp = new CommandRsp(0);
            // 使用响应ID发送命令响应以确认接收命令
            device.getClient().respondCommand(requestId, commandRsp);
            // 检查命令是否为设置报告频率
            if ("setReportingFrequency".equals(commandName)) {
                // 更新睡眠时间以根据参数中的值调整报告频率
                SLEEP_TIME = (int) paras.get("value") * 1000;
            }
        });

        // 启动属性报告进程
        startPropertyReporting();

    }

    private void startPropertyReporting() {
        ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(() -> {
            Random rand = new Random();
            environmentService.setTemperature(10+rand.nextInt(41) );
            environmentService.setHumidity(18 + rand.nextInt(13));

            environmentService.firePropertiesChanged();

            SLEEP_TIME = Math.max(SLEEP_TIME, 1000);
        }, 0, SLEEP_TIME, TimeUnit.MILLISECONDS);
    }

    @Bean
    public EnvironmentService environmentService() {
        return new EnvironmentService();
    }
}
